//
//  NSAttributedString+YY.m
//  YYAtPersonDemo
//
//  Created by Ace on 2017/9/11.
//  Copyright © 2017年 Ace. All rights reserved.
//

#import "NSAttributedString+YY.h"
#import "HEATTextAttachment.h"

@implementation NSAttributedString (YY)

- (NSArray *)getCurrentAtPersonItems {
    __block NSMutableArray *personItems = [NSMutableArray new];
    [self enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, self.length) options:0 usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
        if (value && [value isKindOfClass:[HEATTextAttachment class]]) {
            HEATTextAttachment *textAttachment = value;
            if (textAttachment.personItem) {
                [personItems addObject:textAttachment.personItem];
            }
        }
    }];
    
    return personItems;
}

- (NSDictionary *)getAttachInfo {
    NSMutableDictionary *dict = @{}.mutableCopy;
    NSMutableAttributedString *newStr = [[NSMutableAttributedString alloc] initWithAttributedString:self];
    NSMutableArray *ids = @[].mutableCopy;
    
    [self replaceNameAttribued: newStr ids: ids];
    
    [dict setValue:newStr.string forKey:@"text"];
    [dict setValue:ids forKey:@"ids"];
    return dict;
}

- (void)replaceNameAttribued:(NSMutableAttributedString *)attributedString ids:(NSMutableArray *)idsArr {
    [attributedString enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, attributedString.length) options:0 usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
        if (value && [value isKindOfClass:[HEATTextAttachment class]]) {
            HEATTextAttachment *textAttachment = value;
            if (textAttachment.personItem) {
                [attributedString deleteCharactersInRange:range];
                [attributedString replaceCharactersInRange:NSMakeRange(range.location, 0) withString:textAttachment.personItem.nameATString];
                [attributedString removeAttribute:NSAttachmentAttributeName range:NSMakeRange(range.location, textAttachment.personItem.nameATString.length)];
                *stop = YES;
                [idsArr addObject:textAttachment.personItem.infoId];
                [self replaceNameAttribued:attributedString ids:idsArr];
            }
        }
    }];
}

@end
